const app = getApp()
Page({
  data: {
    specificationRespList: [],
    shopCartGoods: [],
    selData: {
      kc: 0
    },
    showData: {
      salePrice: 0,
      stock: 0
    },
    detailData: {},
    value: '',
    value2: '',
    value3: '',
    value4: '',
    value5: '',
    showMask: false,
    showDetail: false,
    showShopCart: false,
    animationData: {},
    placementPointId: '3',
    commodityRequests: [],
    banners: [{
      id: 1,
      image: '/img/banner.png'
    }],
    shops: [],
    expressFee: 10,
    topNoticeTxt: '',
    activeShop: 1,
    currentGoods: [],
    totalCount: 0,
    totalPrice: 0
  },

  onShow() {
    this.initGoodsData()
  },
  onReady() {
    this.startAnimation()
  },
  startAnimation() {
    const query = wx.createSelectorQuery()
    query.select('.notice-text').boundingClientRect()
    query.exec(res => {
      const textWidth = res[0].width
      const animation = wx.createAnimation({
        duration: 15000,
        timingFunction: 'linear'
      })
      animation.translateX(-textWidth).step()
      this.setData({
        animationData: animation.export()
      })

      setInterval(() => {
        const resetAnim = wx.createAnimation()
        resetAnim.translateX(0).step({
          duration: 0
        })
        this.setData({
          animationData: resetAnim.export()
        })

        setTimeout(() => {
          const newAnim = wx.createAnimation({
            duration: 15000,
            timingFunction: 'linear'
          })
          newAnim.translateX(-textWidth).step()
          this.setData({
            animationData: newAnim.export()
          })
        }, 100)
      }, 15000)
    })
  },

  // 显示蒙版
  showMask() {
    this.setData({
      showDetail: true
    })
    this.setData({
      showMask: true
    })
  },
  dealGoods() {
    console.log(212212)
    let shopCartGoods = this.data.shopCartGoods
    let shops = this.data.shops
    let delIds = []
    for (let i = 0; i < shops.length; i++) {
      let goodsResponseList = shops[i].goodsResponseList
      for (let j = 0; j < goodsResponseList.length; j++) {
        let goodsResponse = goodsResponseList[j]
        let newId = goodsResponse.id
        let specificationRespList = goodsResponse.specificationRespList
        if (specificationRespList === null || specificationRespList === undefined) {
          let count = goodsResponse.count
          if (count != undefined && count === 0) {
            delIds.push(newId)
          } else if (count != undefined && count > 0) {

            let isUpdate = false
            for (let k = 0; k < shopCartGoods.length; k++) {
              let oldId = shopCartGoods[k].id
              if (newId === oldId) {

                shopCartGoods[k].count = count
                isUpdate = true
              }
            }
            if (!isUpdate) {
              shopCartGoods.push(goodsResponse)
            }

          }
        } else {
          for (let k = 0; k < specificationRespList.length; k++) {
            let itemSpe = specificationRespList[k]
            let speCount = itemSpe.count
            let specificationId = itemSpe.id

            let item = {}
            item.id = newId
            item.salePrice = itemSpe.salePrice
            item.count = speCount
            item.value = itemSpe.value
            item.stock = itemSpe.stock
            item.name = goodsResponse.name
            item.value2 = itemSpe.value2
            item.value3 = itemSpe.value3
            item.value4 = itemSpe.value4
            item.value5 = itemSpe.value5
            item.specificationId = specificationId
            item.mainImage = goodsResponse.mainImage
            if (speCount != undefined && speCount === 0) {
              delIds.push(newId)
            } else if (speCount != undefined && speCount > 0) {

              let isUpdate = false
              for (let k = 0; k < shopCartGoods.length; k++) {
                let oldId = shopCartGoods[k].id
                let oldSpecificationId = shopCartGoods[k].specificationId
                if (newId === oldId) {
                  if (specificationId === oldSpecificationId) {
                    shopCartGoods[k].count = speCount
                    isUpdate = true
                  }
                }
              }
              if (!isUpdate) {
                shopCartGoods.push(item)
              }

            }
          }
        }

      }
    }
    if (delIds.length > 0) {
      shopCartGoods = shopCartGoods.filter(x => delIds.indexOf(x.id) < 0)
    }
    this.setData({
      shopCartGoods
    })
  },
  showShopCart() {
    let totalCount = this.data.totalCount
    if (totalCount === 0) {
      return
    }

    // _this.data.shops[0].goodsResponseList
    let showShopCart = this.data.showShopCart
    if (!showShopCart) {
      this.dealGoods()
    }
    let showMask = this.data.showMask
    this.setData({
      showMask: !showMask
    })
    this.setData({
      showShopCart: !showShopCart
    })
    console.log(this.data.shopCartGoods)
  },

  // 隐藏蒙版
  hideMask() {
    this.setData({
      showMask: false
    })
    this.setData({
      showShopCart: false
    })
    this.setData({
      showDetail: false
    })
  },
  handleItemClick2: function (e) {
    const value = e.currentTarget.dataset.value;
    console.log('点击的值:', value);
    // 这里可以添加其他业务逻辑
    this.setData({
      value2: value
    });
    this.updateShowData()
  },
  handleItemClick3: function (e) {
    const value = e.currentTarget.dataset.value;
    console.log('点击的值:', value);
    // 这里可以添加其他业务逻辑
    this.setData({
      value3: value
    });
    this.updateShowData()
  },
  handleItemClick4: function (e) {
    const value = e.currentTarget.dataset.value;
    console.log('点击的值:', value);
    // 这里可以添加其他业务逻辑
    this.setData({
      value4: value
    });
    this.updateShowData()
  },
  handleItemClick5: function (e) {
    const value = e.currentTarget.dataset.value;
    console.log('点击的值:', value);
    // 这里可以添加其他业务逻辑
    this.setData({
      value5: value
    });
    this.updateShowData()
  },
  updateShowData: function (e) {
    let specificationRespList = this.data.detailData.specificationRespList
    let value = this.data.value
    let value2 = this.data.value2
    let value3 = this.data.value3
    let value4 = this.data.value4
    let value5 = this.data.value5
    let isExist = false
    for (let i = 0; i < specificationRespList.length; i++) {
      let item = specificationRespList[i]
      if (value === item.value && value2 == item.value2 && value3 == item.value3 && value4 == item.value4 && value5 == item.value5) {
        this.setData({
          showData: {
            id: item.id,
            stock: item.stock,
            count: item.count,
            salePrice: item.salePrice,
            parentId: this.data.detailData.id
          }
        })
        isExist = true
      }
    }
    if (!isExist) {
      this.setData({
        showData: {
          id: null,
          stock: 0,
          salePrice: 0
        }
      })
    }
  },
  handleItemClick1: function (e) {
    const value = e.currentTarget.dataset.value;
    console.log('点击的值:', value);
    // 这里可以添加其他业务逻辑
    this.setData({
      value: value
    });
    this.updateShowData()
  },
  // 阻止蒙版下层滚动
  preventScroll() {
    return false
  },
  initGoodsData() {
    let placementPointId = wx.getStorageSync('placementPointId')
    if (placementPointId == undefined || placementPointId == null || placementPointId == '') {
      placementPointId = '3'
    }
    console.log(3323)
    let _this = this
    app.goods.goods(placementPointId).then(res => {
      console.log(res)
      if (res.code === 200) {
        wx.setNavigationBarTitle({
          title: res.data.deliveryPointName
        })
        let totalCount = 0
        let totalPrice = 0
        res.data.businessResponseList.forEach(item => {
          let goods = item.goodsResponseList
          goods.forEach(e => {


            let cart = wx.getStorageSync('cart')
            if (cart != undefined && cart != []) {
              _this.setData({
                commodityRequests: cart
              })
              for (let j = 0; j < cart.length; j++) {
                let item2 = cart[j]
                if (e.id === item2.id) {
                  let speId = item2.speId
                  if (speId === null || speId === null || speId === undefined) {
                    e.count = item2.cnt
                    totalCount += item2.cnt
                    totalPrice += item2.cnt * e.salePrice
                  } else {
                    let specificationRespList = e.specificationRespList
                    for (let k = 0; k < specificationRespList.length; k++) {
                      let speItem = specificationRespList[k]
                      if (speId === speItem.id) {
                        speItem.count = item2.cnt
                        totalCount += item2.cnt
                        totalPrice += item2.cnt * speItem.salePrice
                      }
                    }
                  }


                }
              }
            }
          })
        })


        _this.setData({
          expressFee: res.data.expressFee,
          expressDuration: res.data.expressDuration,
          deliveryPointName: res.data.deliveryPointName,
          topNoticeTxt: res.data.topNoticeTxt,
          totalCount,
          totalPrice: totalPrice.toFixed(2),
          shops: res.data.businessResponseList
        })
        console.log(21221)
        if (_this.data.shops.length > 0) {
          _this.setData({
            activeShop: _this.data.shops[0].id,
            currentGoods: _this.data.shops[0].goodsResponseList
          })
        }
      }
    })
  },

  changeShop(e) {
    console.log(e)
    const shopId = e.currentTarget.dataset.id
    let currentShop = this.data.shops.filter(item => item.id === shopId)
    this.setData({
      activeShop: shopId,
      currentGoods: currentShop[0].goodsResponseList
    })
  },

  increaseCount(e) {
    let _this = this
    let id = e.currentTarget.dataset.id.id
    console.log(e.currentTarget.dataset.id)
    let shops = this.data.shops
    for (let i = 0; i < shops.length; i++) {
      const goodsList = shops[i].goodsResponseList
      for (let j = 0; j < goodsList.length; j++) {
        let item = goodsList[j]
        if (id === item.id) {
          let specificationRespList = item.specificationRespList
          console.log(specificationRespList)
          _this.setData({
            specificationRespList
          })
          if (specificationRespList != null && specificationRespList.length > 0) {
            _this.setData({
              detailData: item
            })
            _this.showMask()
            item = specificationRespList[0]
            _this.setData({
              showData: {
                parentId: id,
                id: item.id,
                stock: item.stock,
                salePrice: item.salePrice,
                count: item.count || 0
              },
              value: item.value,
              value2: item.value2,
              value3: item.value3,
              value4: item.value4,
              value5: item.value5
            })

            app.goods.shopCart(id).then(res => {
              if (res.code === 200) {
                let specificationsTitle = res.data.specificationsTitle
                _this.setData({
                  'detailData.specificationsTitle': specificationsTitle
                })
              }
            })
          } else {
            _this.updateGoodsCount(id, 1)
            _this.dealGoods()
          }
          console.log(21221)
        }
      }
    }

    // const id = e.currentTarget.dataset.id
    console.log(e)
    // this.updateGoodsCount(id, 1)
  },
  increaseCount1(e) {
    let _this = this
    console.log(this.data.showData.id)
    let id = e.currentTarget.dataset.id.id
    console.log(e.currentTarget.dataset.id)
    this.updateGoodsCount1(id, null, 1)
    this.dealGoods()
  },
  decreaseCount2(e) {
    let parentId = this.data.showData.parentId
    let shops = this.data.shops
    let stock = this.data.showData.stock
    if (stock === 0) {
      return false;
    }
    for (let i = 0; i < shops.length; i++) {
      const goodsList = shops[i].goodsResponseList
      let goods = goodsList.filter(item => item.id === parentId)[0]
      console.log(goods)
      if (goods) {
        let goodsSpecificationRespList = goods.specificationRespList
        if (goodsSpecificationRespList === undefined || goodsSpecificationRespList === null) {
          goodsSpecificationRespList = []
        }
        let specificationRespList = this.data.specificationRespList
        for (let j = 0; j < specificationRespList.length; j++) {
          let item = specificationRespList[j]
          if (item.id === this.data.showData.id) {
            const newCount = (item.count || 0) - 1
            if (newCount < 0) {
              return
            }
            item.count = newCount
            this.setData({
              'showData.count': newCount
            })
          }
        }
      }
    }
  },
  increaseCount2(e) {
    let parentId = this.data.showData.parentId
    let shops = this.data.shops
    let stock = this.data.showData.stock
    if (stock === 0) {
      return false;
    }
    for (let i = 0; i < shops.length; i++) {
      const goodsList = shops[i].goodsResponseList
      let goods = goodsList.filter(item => item.id === parentId)[0]
      console.log(goods)
      if (goods) {
        let goodsSpecificationRespList = goods.specificationRespList
        if (goodsSpecificationRespList === undefined || goodsSpecificationRespList === null) {
          goodsSpecificationRespList = []
        }
        let specificationRespList = this.data.specificationRespList
        for (let j = 0; j < specificationRespList.length; j++) {
          let item = specificationRespList[j]
          if (item.id === this.data.showData.id) {
            const newCount = (item.count || 0) + 1
            if (newCount < 0) {
              return
            }

            if (item.stock < newCount) {
              return
            }
            item.count = newCount
            this.setData({
              'showData.count': newCount
            })
          }
        }
      }
    }
  },
  increaseCount3(e) {
    this.calculateTotal()
    this.dealGoods()
    this.hideMask()
  },
  decreaseCount1(e) {
    console.log(e)
    let item = e.currentTarget.dataset.id
    this.updateGoodsCount1(item.id, e.currentTarget.dataset.id.specificationId, -1)
    this.dealGoods()
  },
  decreaseCount(e) {
    const id = e.currentTarget.dataset.id
    this.updateGoodsCount(id, -1)
    this.dealGoods()
  },
  updateGoodsCount1(id, speId, delta) {
    console.log(speId)
    const shops = this.data.shops
    for (let i = 0; i < shops.length; i++) {
      const goodsList = shops[i].goodsResponseList
      let goods = goodsList.filter(item => item.id === id)[0]
      console.log(goods)
      if (goods) {
        let specificationRespList = goods.specificationRespList
        if (specificationRespList == null || specificationRespList == undefined) {
          const newCount = (goods.count || 0) + delta
          if (newCount < 0) {
            return
          }

          if (goods.stock < newCount) {
            return
          }
          goods.count = newCount
          this.setData({
            shops,
            currentGoods: goodsList
          }, () => {
            this.calculateTotal()
          })
        } else {
          for (let i = 0; i < specificationRespList.length; i++) {
            goods = specificationRespList[i]
            if (goods.id === speId) {
              const newCount = (goods.count || 0) + delta
              if (newCount < 0) {
                return
              }

              if (goods.stock < newCount) {
                return
              }
              goods.count = newCount
              this.setData({
                shops,
                currentGoods: goodsList
              }, () => {
                this.calculateTotal()
              })
            }
          }
        }

      }
    }

  },
  updateGoodsCount(id, delta) {
    const shops = this.data.shops
    const shopId = this.data.activeShop
    const goodsList = shops.filter(item => item.id === shopId)[0].goodsResponseList
    let goods = goodsList.filter(item => item.id === id)[0]
    console.log(goods)
    if (goods) {
      const newCount = (goods.count || 0) + delta
      if (newCount < 0) {
        return
      }

      if (goods.stock < newCount) {
        return
      }
      goods.count = newCount
      this.setData({
        shops,
        currentGoods: goodsList
      }, () => {
        this.calculateTotal()
      })
    }
  },

  calculateTotal() {
    let cart = []
    let totalCount = 0
    let totalPrice = 0
    this.data.shops.forEach(item => {
      let goods = item.goodsResponseList
      goods.forEach(e => {
        let specificationRespList = e.specificationRespList
        if (specificationRespList === null || specificationRespList === undefined) {
          console.log(e)
          totalCount += e.count || 0
          totalPrice += (e.count || 0) * e.salePrice
          if (e.count != undefined && e.count != null && e.count > 0) {
            let eCart = {}
            eCart.id = e.id
            eCart.cnt = e.count
            eCart.mainImage = e.mainImage
            eCart.name = e.name
            eCart.salePrice = e.salePrice
            cart.push(eCart)
          }
        } else {
          for (let i = 0; i < specificationRespList.length; i++) {
            let spe = specificationRespList[i]
            if (spe.count != undefined && spe.count != null && spe.count > 0) {
              totalCount += spe.count || 0
              totalPrice += (spe.count || 0) * spe.salePrice
              let eCart = {}
              eCart.id = e.id
              eCart.speId = spe.id
              eCart.cnt = spe.count
              eCart.value = spe.value
              eCart.value2 = spe.value2
              eCart.value3 = spe.value3
              eCart.value4 = spe.value4
              eCart.value5 = spe.value5
              eCart.mainImage = e.mainImage
              eCart.name = e.name
              eCart.salePrice = spe.salePrice
              cart.push(eCart)
            }
          }
        }
      })
    })
    console.log(totalPrice + "ltq")
    this.setData({
      totalCount,
      totalPrice: totalPrice.toFixed(2),
      commodityRequests: cart
    })
    wx.setStorageSync('cart', cart)
  },
  onLoad(options) {

  },
  confirmOrder() {
    this.setData({
      showMask: false
    })
    this.setData({
      showShopCart: false
    })
    if (this.data.totalCount === 0) {
      wx.showToast({
        title: '请先选择商品',
        icon: 'none'
      })
      return
    }
    let _this = this
    let param = {}
    param.expressFee = _this.data.expressFee
    param.price = _this.data.totalPrice
    param.num = _this.data.totalCount
    param.totalPrice = (Number(_this.data.expressFee) + Number(_this.data.totalPrice)).toFixed(2)
    param.placementPointId = _this.data.placementPointId
    param.expressDuration = _this.data.expressDuration
    param.deliveryPointName = _this.data.deliveryPointName
    console.log(param.expressDuration)
    param.commodityRequests = _this.data.commodityRequests
    wx.navigateTo({
      url: `/pages/order/order?data=${encodeURIComponent(JSON.stringify(param))}`
    })
  },

  onPullDownRefresh() {
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})
